//app.js
App({
  onLaunch: function (options) {
    //调用API从本地缓存中获取数据
    this.loginUser()
  },
  getUserInfo: function (cb) {
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      this.loginUser()
    }
  },
  loginUser() {
    var that = this
    wx.login({
      success(res) {
        var open_id = null
        wx.request({
          url: "https://kaifan.chuanggj.com/wechat/get_code",
          data: {
            code: res.code
          },
          success(s) {
            open_id = s.data.res.openid
            if (!open_id || open_id === null) {
              return false
            }
            wx.getUserInfo({
              success(res) {
                var data = res.userInfo
                data.open_id = open_id
                that.globalData.userInfo = res.userInfo
                typeof cb == "function" && cb(that.globalData.userInfo)
                wx.request({
                  url: "https://kaifan.chuanggj.com/wechat/login",
                  data: { data: data },
                  method: "POST",
                  header: {
                    'content-type': 'application/json'
                  },
                  success(rs) {
                    that.globalData.userInfo = rs.data.user
                    wx.setStorageSync("token", rs.data.token)
                    //cb(rs)
                  },
                  fail(res) {
                    return res
                  }
                })
              }
            })
          }
        })
      }
    })
  },
  globalData: {
    userInfo: null
  }
})
